<template>
  <a-card :bordered="false" v-show="visible" class="card" :title="modalTitle">
    <a-row :gutter="48" slot="extra">
      <a-col :md="48" :sm="48">
        <span class="table-page-search-submitButtons" style="float: right">
          <a-button type="primary" @click="save()">提交</a-button>
          <a-button style="margin-left: 8px" @click="handleCancel()">返回</a-button>
        </span>
      </a-col>
    </a-row>

    <title-divider title="基本信息" width="90px"></title-divider>
    <a-form :form="form">
      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
        <a-input v-decorator="['parentId']" type="hidden"/>
      </a-form-item>

      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="设备（新号）"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['no', {rules: [{required: true, message: '不能为空'}]}]" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="设备（旧号）"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['zbh', {rules: [{required: false, message: '不能为空'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="设备名称"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['name', {rules: [{required: true, message: '设备名称不能为空'}]}]" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="型号"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['model', {rules: [{required: true, message: '设备型号不能为空'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <title-divider title="试车数据记录" width="120px"></title-divider>
      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="连续运转时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              :rows="4"
              suffix="分钟"
              v-decorator="['fdjh']"/>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="启动电流"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              suffix="A"
              v-decorator="['zz']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="压力"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              :rows="4"
              suffix="进口"
              v-decorator="['fdjh']"/>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="压力"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              suffix="出口"
              v-decorator="['zz']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="轴承温度"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              :rows="4"
              suffix="前"
              v-decorator="['fdjh']"/>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="轴承温度"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              suffix="后"
              v-decorator="['zz']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="电压"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              :rows="4"
              suffix="V"
              v-decorator="['fdjh']"/>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="电流"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              suffix="A"
              v-decorator="['zz']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <title-divider title="试车意见" width="120px"></title-divider>
      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="24" :md="24" :sm="24">
          <a-form-item
            label="试车意见"
            :labelCol="BaseTool.Constant.labelCol2"
            :wrapperCol="BaseTool.Constant.wrapperCol2"
          >
            <a-textarea
              :rows="4"
              v-decorator="['fdjh']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <title-divider title="试车记录文件" width="120px"></title-divider>
      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="试车文件"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-upload
              :action="uploadUrl"
              :multiple="true"
              :file-list="this.defaultRepairFileList"
              @change="handleRepairFileChange"
              :headers="headers"
            >
              <a-button> <a-icon type="upload" /> 选择上传文件 </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="试车照片"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-upload
              :action="uploadUrl"
              :multiple="true"
              :file-list="this.defaultSbFileList"
              @change="handleSbFileChange"
              accept="image/*"
              :headers="headers"
            >
              <a-button> <a-icon type="upload" /> 选择上传文件 </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { addSbInfo, updateSbInfo, fetchSbInfo, copySbInfo } from '@/api/sb/info'
import BaseTool from '../../../../utils/tool'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Vue from 'vue'
import { uploadUrl } from '@/api/upms/file'
import DetailList from '@/components/tools/DetailList'
const DetailListItem = DetailList.Item

export default {
  name: 'BaseSbInfo',
  components: {
    DetailList,
    DetailListItem
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      areaList: {},
      companyList: {},
      paramList: [],
      projectList: {},
      deptList: {},
      groupList: {},
      visible: false,
      sbTypeTreeData: [],
      // sbInfoTreeData: [],
      // sourceSbInfoTreeData: [],
      // sbPositionTreeData: [],
      depreciationTypeMap: {},
      sourceTypeMap: {},
      levelMap: {},
      rlTypeMap: {},
      colorMap: {},
      useTypeMap: {},
      statusMap: {},
      isChildMap: {},
      isShowMap: {},
      isFinancingMap: {},
      userList: {},
      unitMap: {},
      sbInfoSelectType: null,
      repairFileList: [], // 维修手册
      defaultRepairFileList: [],
      defaultUseFileList: [],
      defaultRecheckFileList: [],
      defaultSbFileList: [],
      useFileList: [], // 使用手册
      recheckFileList: [], // 验收手册
      sbFileList: [], // 设备图片,
      uploadUrl: uploadUrl,
      qrcodesrc: null,
      id: null,
      fileList: [],
      type: null,
      headers: {
        Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN)
      }
    }
  },
  props: {
    useType: {
      type: Number,
      default: 3
    }
  },
  created () {
    this.depreciationTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_DEPRECIATIONTYPE)
    this.levelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_LEVEL)
    this.colorMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_COLOR)
    this.rlTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.RANLIAO_TYPE)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_INFO_STATUS)
    this.unitMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_UNIT)
  },
  methods: {
    base (record, type) {
      // 清除文件列表
      this.visible = true
      // 选择框查询条件
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.qrcodesrc = null
        this.modalTitle = '添加'
        this.clearFileList()
        return
      }
      this.useType = record.useType
      this.modalTitle = '编辑'
      this.id = record.id
      this.qrcodesrc = record.qrCode
      this.repairFileList = record.repairFileList
      this.useFileList = record.useFileList
      this.recheckFileList = record.recheckFileList
      this.sbFileList = record.sbFileList
      this.defaultRepairFileList = this.BaseTool.UPLOAD.transImg(this.repairFileList)
      this.defaultUseFileList = this.BaseTool.UPLOAD.transImg(this.useFileList)
      this.defaultRecheckFileList = this.BaseTool.UPLOAD.transImg(this.recheckFileList)
      this.defaultSbFileList = this.BaseTool.UPLOAD.transImg(this.sbFileList)
      this.paramList = JSON.parse(record.paramList)
      if (type === 1) {
        this.type = type
        this.modalTitle = '复制'
        this.qrcodesrc = null
        record.no = null
        this.clearFileList()
      }

      const { form: { setFieldsValue } } = this
      // 日期处理
      // record.buyDate = this.BaseTool.Moment(record.buyDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      // record.startDate = this.BaseTool.Moment(record.startDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      // record.nextCheckDate = this.BaseTool.Moment(record.nextCheckDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      // record.guaranteeDate = this.BaseTool.Moment(record.guaranteeDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      // record.retirementDate = this.BaseTool.Moment(record.retirementDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)

      // record.lastRepaireTime = this.BaseTool.Moment(record.lastRepaireTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      // record.lastBaoyangTime = this.BaseTool.Moment(record.lastBaoyangTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      if (record.buyDate != null) {
        record.buyDate = this.BaseTool.Moment(record.buyDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        this.$nextTick(() => {
          setFieldsValue(Object.assign(pick(record, [
            'buyDate'
          ])))
        })
      }
      if (record.startDate != null) {
        record.startDate = this.BaseTool.Moment(record.startDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        this.$nextTick(() => {
          setFieldsValue(Object.assign(pick(record, [
            'startDate'
          ])))
        })
      }
      if (record.checkDate != null) {
        record.checkDate = this.BaseTool.Moment(record.checkDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        this.$nextTick(() => {
          setFieldsValue(Object.assign(pick(record, [
            'checkDate'
          ])))
        })
      }
      if (record.nextCheckDate != null) {
        record.nextCheckDate = this.BaseTool.Moment(record.nextCheckDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        this.$nextTick(() => {
          setFieldsValue(Object.assign(pick(record, [
            'nextCheckDate'
          ])))
        })
      }
      if (record.retirementDate != null) {
        record.retirementDate = this.BaseTool.Moment(record.retirementDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        this.$nextTick(() => {
          setFieldsValue(Object.assign(pick(record, [
            'retirementDate'
          ])))
        })
      }
      if (record.registerDate != null) {
        record.registerDate = this.BaseTool.Moment(record.registerDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        this.$nextTick(() => {
          setFieldsValue(Object.assign(pick(record, [
            'registerDate'
          ])))
        })
      }
      record.unitName = this.BaseTool.Object.getField(this.unitMap, record.unit)
      record.useTypeName = this.BaseTool.Object.getField(this.useTypeMap, record.useType)

      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'no',
          'parentId',
          'parentSbName',
          'isChild',
          'isShow',
          'isFinancing',
          'financingNo',
          'financingNoTwo',
          'financingNoThird',
          'financingNoFour',
          'financingNoFive',
          'name',
          'model',
          'cph',
          'positionId',
          'producerName',
          'useArea',
          'useCompany',
          'useProject',
          'useDept',
          'saveUser',
          'repairUser',
          'useGroup',
          'typeId',
          'level',
          'initialValue',
          // 'cutValue',
          'producerId',
          // 'sourceType',
          'unit',
          'buyDate',
          'startDate',
          'zbh',
          // 'wbFile',
          // 'useFile',
          // 'checkFile',
          // 'sbImage',
          'status',
          'remark',
          'zzh',
          'zz',
          'zjm',
          'jbdh',
          'useType',
          'cardNo',
          'fdjxh',
          'checkDate',
          'checkPeriod',
          'nextCheckDate',
          'dph',
          'zaiz',
          'rlType',
          'color',
          'sbdh',
          'seatNumber',
          'registerNo',
          'characterType',
          'usedNo',
          'supplier',
          'repairUserSecond',
          'batchNo',
          'workYear',
          'retirementDate',
          'registerDate'

        ])))
      })
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        // 日期数据的处理
        values.buyDate = BaseTool.Date.formatter(values.buyDate, BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.startDate = BaseTool.Date.formatter(values.startDate, BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.checkDate = BaseTool.Date.formatter(values.checkDate, BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.nextCheckDate = BaseTool.Date.formatter(values.nextCheckDate, BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.guaranteeDate = BaseTool.Date.formatter(values.guaranteeDate, BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.retirementDate = BaseTool.Date.formatter(values.retirementDate, BaseTool.Date.PICKER_NORM_DATE_PATTERN)

        values.lastRepaireTime = this.BaseTool.Date.formatter(values.lastRepaireTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.lastBaoyangTime = this.BaseTool.Date.formatter(values.lastBaoyangTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.spDate = this.BaseTool.Date.formatter(values.spDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.jbdDate = this.BaseTool.Date.formatter(values.jbdDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.sbdDate = this.BaseTool.Date.formatter(values.sbdDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.sbDate = this.BaseTool.Date.formatter(values.sbDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)

        // 上传文件
        values.repairFileList = this.repairFileList
        values.useFileList = this.useFileList
        values.recheckFileList = this.recheckFileList
        values.sbFileList = this.sbFileList
        values.paramList = JSON.stringify(this.paramList)
        values.useType = this.useType
        if (this.BaseTool.String.isBlank(values.id)) {
          addSbInfo(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
            this.confirmLoading = false
          })
        } else {
          if (this.type == null) {
            updateSbInfo(values)
              .then(() => {
                this.handleCancel(values)
              }).catch(() => {
              this.confirmLoading = false
            })
          } else {
            copySbInfo(values)
              .then(() => {
                this.handleCancel(values)
              }).catch(() => {
              this.confirmLoading = false
            })
          }
        }
      })
    },
    getQrcodeSrc () {
      console.log(111, 22)
    },
    handleCancel () {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok')
    },
    handleFresh () {
      fetchSbInfo({ id: this.id }).then(res => {
        const { form: { setFieldsValue } } = this
        const record = res.data
        this.$nextTick(() => {
          setFieldsValue(Object.assign(pick(record, [
            'zjm',
            'jbdh'
          ])))
        })
      })
    },

    beforeRecheckFileListUpload (file) {
      const reg = /\.(xls|xlsx)(\?.*)?$/
      return new Promise((resolve, reject) => {
        if (reg.test(file.name)) {
          this.recheckFileList = [file]
          return true
        } else {
          this.$message.error(`请上传正确的xls|xlsx文件`)
          reject(new Error('请上传正确的xls|xlsx文件'))
          return false
        }
      })
    },
    beforeUploadPic (file) {
      const reg = /\.(jpg|jpeg|png)(\?.*)?$/
      return new Promise((resolve, reject) => {
        if (reg.test(file.name)) {
          this.sbFileList = [file]
          return true
        } else {
          this.$message.error(`请上传正确的jpg|jpeg|png文件`)
          reject(new Error('请上传正确的jpg|jpeg|png文件'))
          return false
        }
      })
    },
    clearFileList () {
      this.repairFileList = []
      this.useFileList = []
      this.recheckFileList = []
      this.sbFileList = []
    },
    handleRepairFileChange (info) {
      this.defaultRepairFileList = info.fileList
      this.repairFileList = this.setFileList(info, 1)
    },
    handleUseFileChange (info) {
      this.defaultUseFileList = info.fileList
      this.useFileList = this.setFileList(info, 2)
    },
    handleRecheckFileChange (info) {
      this.defaultRecheckFileList = info.fileList
      this.recheckFileList = this.setFileList(info, 3)
    },
    handleSbFileChange (info) {
      this.defaultSbFileList = info.fileList
      this.sbFileList = this.setFileList(info, 4)
    },
    setFileList1 (info, type) {
      const fileList = [...info.fileList]
      const file = [...info.file]
      if (file.status === 'done') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'removed') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'error') {
        this.$message.error('上传失败')
        return []
      }
    },
    clearParent () {
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'parentId': null,
          'parentSbName': null
        }))
      })
    },
    setFileList (info, type) {
      // { file, fileList }

      const file = info.file
      const fileList = info.fileList
      // fileList = fileList.slice(-2)
      // console.log(111, this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type))

      if (file.status === 'done') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'removed') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'error') {
        this.$message.error('上传失败')
        return null
      }
    }
  }
}
</script>
